package openGl;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.GLUtils;
import android.util.Log;

import java.nio.FloatBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import customview.ike.com.customviewproject.R;
import camera.OpenGl.utils.ByteBufferUtils;

import static android.opengl.GLES20.GL_LINEAR_MIPMAP_LINEAR;
import static android.opengl.GLES20.GL_TRIANGLE_FAN;
import static android.opengl.GLES20.glActiveTexture;
import static android.opengl.GLES20.glClear;
import static android.opengl.GLES20.glClearColor;
import static android.opengl.GLES20.glDrawArrays;
import static android.opengl.GLES20.glUniform1i;
import static android.opengl.GLES20.glUseProgram;

/**
 * Created by Administrator on 2017/12/27.
 */

public class TexureRender implements GLSurfaceView.Renderer {
    private String Tag = "TexureRender";
    /**
     * 顶点着色器
     */
    public final String vertexShaderCode = "uniform mat4 u_Matrix;\n" +
            "\n" +
            "attribute vec4 a_Position;  \n" +
            "attribute vec2 a_TextureCoordinates;\n" +
            "\n" +
            "varying vec2 v_TextureCoordinates;\n" +
            "\n" +
            "void main()                    \n" +
            "{                            \n" +
            "    v_TextureCoordinates = a_TextureCoordinates;\t  \t  \n" +
            "    gl_Position = u_Matrix * a_Position;    \n" +
            "} ";
    /**
     * 片元着色器
     */
    public final String fragmentShaderCode = "precision mediump float; \n" +
            "      \t \t\t\t\t\n" +
            "uniform sampler2D u_TextureUnit;      \t \t\t\t\t\t\t\t\t\n" +
            "varying vec2 v_TextureCoordinates;      \t   \t\t\t\t\t\t\t\t\n" +
            "  \n" +
            "void main()                    \t\t\n" +
            "{                              \t\n" +
            "    gl_FragColor = texture2D(u_TextureUnit, v_TextureCoordinates);                           \t\t\n" +
            "}";
    private final String simple_vertexShaderCode="precision mediump float; \n" +
            "      \t \t\t\t\t\t\t\t\t\n" +
            "varying vec4 v_Color;      \t   \t\t\t\t\t\t\t\t\n" +
            "  \n" +
            "void main()                    \t\t\n" +
            "{                              \t\n" +
            "    gl_FragColor = v_Color;                                  \t\t\n" +
            "}" ;
    private final String simple_fragmentShaderCode="uniform mat4 u_Matrix;\n" +
            "\n" +
            "attribute vec4 a_Position;  \n" +
            "attribute vec4 a_Color;\n" +
            "\n" +
            "varying vec4 v_Color;\n" +
            "\n" +
            "void main()                    \n" +
            "{                            \n" +
            "    v_Color = a_Color;\n" +
            "\t  \t  \n" +
            "    gl_Position = u_Matrix * a_Position;\n" +
            "    gl_PointSize = 10.0;          \n" +
            "}          ";
    
    private float[] tableData = {
            0f, 0f,
            -0.5f, -0.8f,
            0.5f, -0.8f, 
            0.5f, 0.8f,
            -0.5f, 0.8f, 
            -0.5f, -0.8f
    };
    private float[] sTDatas = {
            0.5f, 0.5f,
            0f, 0.9f,
            1f, 0.9f,
            1f, 0.1f,
            0f, 0.1f,
            0f, 0.9f
    };

    private FloatBuffer tableBuffer;
    private FloatBuffer sTDataBuffer;
    private Context mContext;
    private int texture;
    private int a_textureCoordinates;
    private int u_textureUnit;

    public TexureRender(Context context) {
        this.mContext = context;
        tableBuffer = ByteBufferUtils.makeFloteByteBuffer(tableData);
        sTDataBuffer=ByteBufferUtils.makeFloteByteBuffer(sTDatas);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        glClearColor(0.5f,0.5f,0.5f,0.5f);
        int program = GLES20.glCreateProgram();
        int vertexShader = OpenGlUtils.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
        int fragmentShader = OpenGlUtils.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);
        Log.e(Tag, "vertexShader:" + vertexShader);
        Log.e(Tag, "fragmentShader:" + fragmentShader);
        GLES20.glAttachShader(program, vertexShader);
        GLES20.glAttachShader(program, fragmentShader);
        GLES20.glLinkProgram(program);
        glUseProgram(program);

        //获取uniform 属性值
        u_textureUnit = GLES20.glGetUniformLocation(program, "u_TextureUnit");
        int u_matrix = GLES20.glGetUniformLocation(program, "u_Matrix");
        //获取attribute 属性的值
        int a_position = GLES20.glGetAttribLocation(program, "a_Position");
        a_textureCoordinates = GLES20.glGetAttribLocation(program, "a_TextureCoordinates");

        //设置顶点着色器信息
        GLES20.glEnableVertexAttribArray(a_position);
        tableBuffer.position(0);
        GLES20.glVertexAttribPointer(a_position, 2, GLES20.GL_FLOAT, false, 0, tableBuffer);

        //设置纹理坐标信息（配置S,T）
        GLES20.glEnableVertexAttribArray(a_textureCoordinates);
        //设置纹理坐标的指针偏移量（2的位置的偏移，因为每组数据中，ST数据在后两位（2+2））
       // tableBuffer.position(2);
        GLES20.glVertexAttribPointer(a_textureCoordinates, 2, GLES20.GL_FLOAT, false, 0, sTDataBuffer);
        texture = createTexture();


    }

    /**
     * 加载纹理图片
     */
    private int createTexture() {

        int[] textureId = new int[1];
        //生成纹理对象
        GLES20.glGenTextures(1, textureId, 0);
        Log.e(Tag, "纹理对象id:" + textureId[0]);
        //加载本地图片生成Bitmap对象.openGl只能加载原始数据而不是压缩数据
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;//设置获取图片的原始数据，而不是压缩数据
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.air_hockey_surface, options);
        if (bitmap == null) {
            Log.e(Tag, "图片加载失败");
        }
        //绑定纹理对象
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId[0]);
        //设置纹理图片显示的时候的过滤器
        //设置图片放大的时候图片的处理方式(三线性过滤)
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        //设置图片缩小的时候图片的处理方式(双线性过滤)
        GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
        //加载图片到openGl中
        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
        bitmap.recycle();
        //生成MIP贴图
        GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
        //解除与纹理对象的绑定(0表示解除绑定)
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
        return textureId[0];
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
    }

    @Override
    public void onDrawFrame(GL10 gl) {
        glClear(GLES20.GL_COLOR_BUFFER_BIT);

//        //选定绘制纹理的纹理单元
        glActiveTexture(GLES20.GL_TEXTURE0);
        //将纹理单元与，纹理对象绑定
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,texture);
        //将纹理单元传递给u_textureUnit进行渲染显示
        glUniform1i(u_textureUnit,0);
        //绘制桌子
        glDrawArrays(GL_TRIANGLE_FAN, 0, 6);


    }
}
